package xin.nick.common.util;

import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import xin.nick.common.entity.LoginUser;
import xin.nick.common.entity.ResultCode;

import java.util.Objects;
import java.util.Optional;

/**
 * @author Nick
 * @date 2022/8/10
 */
public class SecurityUtil {

    /**
     * 获取当前用户登录信息
     * @return
     */
    public static LoginUser getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        MyAssert.notNull(authentication, ResultCode.UNAUTHORIZED);
        LoginUser loginUser = (LoginUser)authentication.getPrincipal();
        return loginUser;
    }

    /**
     * 获取当前用户id
     * @return
     */
    public static Long getCurrentUserId() {
        LoginUser currentUser = getCurrentUser();
        Long userId = currentUser.getUserId();
        return userId;
    }

    /**
     * 获取当前用户登录信息,不检查登录状态
     * @return
     */
    public static LoginUser getCurrentUserNoCheck() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (Objects.isNull(authentication)) {
            return null;
        }
        Object principal = authentication.getPrincipal();
        LoginUser loginUser = null;
        if (principal instanceof LoginUser) {
            loginUser = (LoginUser) authentication.getPrincipal();
        }
        if (Objects.isNull(loginUser)) {
            return null;
        }
        return loginUser;
    }

    /**
     * 获取当前用户id,不检查登录状态
     * @return
     */
    public static Long getCurrentUserIdNoCheck() {
        LoginUser currentUser = getCurrentUserNoCheck();
        if (Objects.isNull(currentUser)) {
            return null;
        }
        Long userId = currentUser.getUserId();
        return userId;
    }

}
